<?php
/**
 * Maven Manage Catalog SPRichard - Import Product Shell Script
 *
 * @category    Maven
 * @package     Mage_Shell
 * @author      Maven Team <info@maven-infosoft.com>
 */
require_once('abstract.php');

function p($ar, $exit=1)
{
	print "<pre>";
	print_r($ar);
	print "</pre>";
	if($exit == 1) 	exit;
}
function m($obj, $exit=1)
{
	print "<pre>";
	echo "Class : ". get_class($obj). "<BR/>";
	print_r(get_class_methods(get_class($obj)));
	print "</pre>";
	if($exit == 1) 	exit;
}


class Maven_Shell_Import_SprProduct extends Mage_Shell_Abstract
{

	public $mc_id;


	/**
	 * @var No. of Child Process Instances
	 */
	protected $_processInstance = 10;
	protected $_limitor = 200;
	protected $_batchSplitSize = 20;

	/**
	 * @var no. of product update in collection
	 */
	protected $_pageSize = 20;


	public function __construct()
	{
		parent::__construct();
		set_time_limit(0);
		ini_set('memory_limit','6048M');
	}

	/**
	 * @param int $total
	 * @param int $instance
	 * @return number - limit of the batch
	 */
	public function getLimitor($total)
	{
		$limit_ar = array(100, 500, 1000, 5000, 10000, 20000, 30000,50000, 100000);
		foreach ($limit_ar as $ele) {
			if(ceil($total/$ele) < $this->_processInstance) {
				return $ele;
			}
		}
	}

	public function getLastManageCatalogId()
	{
		$cols = Mage::getResourceModel('managecatalogspr/managecatalog')->getLast('Price');
		if(isset($cols['managecatalog_id'])) {
			return $cols['managecatalog_id'];
		}
	}

	public function isRunning($title)
	{
		$cols = Mage::getResourceModel('managecatalogspr/managecatalog')->getLast($title);
		if(isset($cols['status']) && $cols['status']==0){
			return true;
		}else {
			return false;
		}
	}

	public function startBatch()
	{
		$startLimit = (int) $this->getArg('from');
		$limitor = (int) $this->getArg('limit');
		if(!$this->getArg('mc_id')) {
			Mage::log("mc_id not found in arguement which is start from ".$startLimit);
			return false;
		}
		$mc_id = (int) $this->getArg('mc_id');

		$mc = Mage::getModel('managecatalogspr/import');

		$implog = Mage::getModel('managecatalogspr/importlog')
		->getCollection()
		->addFieldToFilter('estatus', array('neq' => 1))
		->addFieldToFilter('id', array('gteq' => $startLimit))
		->addFieldToFilter('id', array('lteq' => ($startLimit + $limitor)))
		->setOrder('id', 'ASC');

		$counter = 0;
		$total = $implog->count();


		if($total == 0 ) {
			Mage::log("Product Database operation Already Done!", 7, Mage::getStoreConfig('managecatalog/price_file/log_file'));
			echo " => From ".$this->getArg('from')." to ".($this->getArg('from') + $this->getArg('limit'))." update Already Done!";
			exit;
		}else {
			$i=1;
			while($counter < $total) {
				$implog = Mage::getModel('managecatalogspr/importlog')
				->getCollection()
				->addFieldToFilter('estatus', array('neq' => 1))
				->addFieldToFilter('id', array('gteq' => $startLimit))
				->addFieldToFilter('id', array('lteq' => ($startLimit + $limitor)))
				->setOrder('id', 'ASC')
				->setPageSize($this->_pageSize)->setCurPage($i++)
				->load();
				foreach ($implog as $data) {
					$status=0;
					$attemp=0;
					while(1) { // untill deadlock not resolve.
						// product save through command line.
						$obj = Mage::getModel('managecatalogspr/ProductSave');
						$obj->loadProduct(array('id'=> $data->getId()));
						$status = $obj->saveProduct();
						$attemp++;
						if($status!=0 || $attemp==5) break;
					}
					//if($status==1) { // deadlock will reprocess.
					$counter++;
					//}
					if($counter%10==0) {
						$mc->savePriceEntry($insObj='',$mc_id);
					}
				}
				$counter++;
			}
			$mc->savePriceEntry($insObj='',$mc_id,1);
			unset($obj);
			echo "Product update Child process From ".$this->getArg('from')." to ".($this->getArg('from') + $this->getArg('limit'))." completed!";
		}
	}

	public function checkSpexliveService()
	 {		
			$getAppId=Mage::getStoreConfig('managecatalogspr/price_file/spex_app_id');
            $sku='AAG7002005';
            $url = "http://ws.spexlive.net/service/rest/catalog?method=getProduct&appId=".$getAppId."&skuNumberType=SP%20Richards&skuNumberVal=".$sku."&catalog=na&descriptionTypes=all&skuTypes=all&accessoryMax=0&displayTemplate=0&resourceType=all";
        	try{
    				$webClient = new Zend_Http_Client();
    				$webClient->setUri($url);
    				$webClient->setMethod(Zend_Http_Client::GET);
    				$webClient->setHeaders('Content-Type: text/xml; charset=UTF-8');
    			    $response = $webClient->request();
                    if ($response->isError()){
    					$this->errorSystemMessage =" Response Message: ".$response->getMessage();
    					return false;
                   	}
					return true;
    			  }
    			 catch (Exception $e) {
    				$this->errorSystemMessage = "Warning: cannot connect to Spexlive.";
    				return false;
           }
		
	 }
	/**
	 * Insert file lines in the temporary table.
	 * @return string|Mage_Core_Model_Abstract|string
	 */
	 
	public function insertion($file='')
	{
	    if(!$this->checkSpexliveService())
		 {
			print $msg = "Error for retriving data, please check application ID for Etilize Web service.";
			return false;
		 }
		if($this->isRunning('Price')) {
			print $msg = "Price update process is running!";
			return false;
		}
		try {
			// INSERT PRODUCTS
			$insObj = Mage::getModel('managecatalogspr/InsertProduct'); //new InsertProduct();
			$insObj->cleanLog();
			if($file!='') {
				$insObj->processFile($file);
			}else {
                $insObj->downloadFiles();
				$insObj->process();
			}
			$imp = Mage::getModel('managecatalogspr/import');
			$this->mc_id = $imp->savePriceEntry($insObj);
			return $insObj;
		} catch (Exception $e) {
			if(isset($this->mc_id)) {
				$imp->savePriceEntry($insObj,$this->mc_id,3);
			}
			print "Exception Thrown - ".$e->getMessage();
			return false;
		}
	}


	/**
	 * Execute command in multi threading manner (Linux).
	 * Run as single instance for the windows OS.
	 * @return unknown_type
	 */
	public function execCommand()
	{
		/* @var total:  Total Records: Pending(0), Success(1), Fail(2), Deadlock(3) */
		$total = Mage::getResourceModel('managecatalogspr/importlog')->getCountData();
		$limitor = $this->_limitor; //500; //$this->getLimitor($total);

		$startLimit = 0;

		if($total > 0) {
			$cmd = '';
			$batches = ceil($total / $limitor);

			//$this->_batchSplitSize;
			for($i=0; $i<$batches; $i++) {
				$loopCount = ceil($limitor / $this->_batchSplitSize);
				$cmds = array();
				for($j=0; $j<$loopCount; $j++) {
					$cmds[] = "php ".__FILE__." --from ".$startLimit." --limit ".$this->_batchSplitSize." --mc_id ".$this->mc_id;
					$startLimit+=$this->_batchSplitSize;
				}

				if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { // DOS OS - Single task
					foreach ($cmds as $cmd) {
						system($cmd);
					}
				}else { // Linux - multi tasking
					$cmd = implode("& ",$cmds);
					system($cmd);
				}
				//Process deadlock detected products.
				system("php ".__FILE__." --from 0 --limit ".$startLimit." --mc_id ".$this->mc_id);
			}
		}
	}
	
	public function insertionPrice()
	{
			try {
		    print $msg = "Price import process is running! \n";  
			// INSERT PRODUCTS PRICE
			$priceObj = Mage::getModel('managecatalogspr/InsertProduct'); //new InsertProduct();
			$priceObj->cleanPriceLog();
			$priceObj->downloadFiles();
            $priceObj->processPrice();
       	} catch (Exception $e) {
			print "Exception Thrown - ".$e->getMessage();
		}
	}
	public function sprStockUpdate()
	{
		$stock = Mage::getModel('managecatalogspr/import');
		$stock->runSprStock();
	}
	
	
	/* (non-PHPdoc)
	 * @see shell/Mage_Shell_Abstract#run()
	 * example:
	 * php import_sprproduct.php --start
	 * php import_sprproduct.php --price
	 * php import_sprproduct.php --from 0 --limit 10000 --mc_id 5
	 * php import_sprproduct.php --testFile PRICE.TXT
	 * php import_sprproduct.php --resume // resume the remain updates from the table
	 * -- Test product by the id
	 * php import_sprproduct.php --testProduct 2
     * php import_sprproduct.php --sprstockupdate
	 */
	public function run()
	{
    
		$isFullProcess=0;

		try {
			if($this->getArg('start')) { // Start the update Parent Process
				if($insObj = $this->insertion()) {
					$this->execCommand();
					echo "Product update process completed!";
					$isFullProcess=1;
				}
			} else if($this->getArg('price')){ //call for price update daily
               $priceObj = $this->insertionPrice();
			}else if($this->getArg('from')!='') { // Call for the Child process start from
				$this->startBatch();
			}else if($this->getArg('testProduct')) { // Testing for the single product.
                 
               	$obj = Mage::getModel('managecatalogspr/ProductSave');
				$obj->loadProduct(array('id'=> $this->getArg('testProduct')));
				$obj->saveProduct();
			}else if ($this->getArg('testFile')) { // Testing for the preuploaded file in the var/import/PRICE/ folder.
				if($this->isRunning('Price')) {
					print $msg = "Price update process is running!";
				}else {
					$insObj = $this->insertion(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::PRICE_FOLDER).$this->getArg('testFile'));
					$this->execCommand();
					echo "Product update process completed!";
					$isFullProcess=1;
				}
			}else if ($this->getArg('resume')) { // update from the import table
				$this->mc_id = $this->getLastManageCatalogId();
				$this->execCommand();
				echo "Product update process completed!";
				$isFullProcess=1;
			}else if($this->getArg('sprstockupdate')){
			     $this->sprStockUpdate();
			}else if ($this->getArg('test')) {
			    echo "hi";
                exit;
			}	
		}catch (Exception $e) {
			print "Error :". $e;
			//print "Error :". $e->getMessage();
		}
		if($isFullProcess==1) {
			$this->stockUpdate(); //stock update and refresh cache and indices
		}
	}
}

$obj = new Maven_Shell_Import_SprProduct();
$obj->run();